<%@ page language="java" contentType="text/html; charset=utf-8"
         pageEncoding="utf-8"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>用户管理</title>
  <link rel="stylesheet" type="text/css" href="<%=path %>/style/easyui.css">
  <link rel="stylesheet" type="text/css" href="<%=path %>/style/icon.css">
  <link rel="stylesheet" type="text/css" href="<%=path %>/style/neweasyui/themes/gray/panel.css">
  <link rel="stylesheet" type="text/css" href="<%=path %>/style/neweasyui/themes/gray/window.css">
  
  <link rel="stylesheet" type="text/css" href="<%=path %>/script/zTree_v3/css/zTreeStyle/zTreeStyle.css" >
  <link rel="stylesheet" type="text/css" href="<%=path %>/script/zTree_v3/css/demo.css" >
  
  <script type="text/javascript" src="<%=path %>/script/1.11.1.js"></script>
  <script type="text/javascript" src="<%=path %>/script/jquery.easyui.min.js"></script>
  <script type="text/javascript" src="<%=path %>/script/jquery.easyui.min.js"></script>
  <script type="text/javascript" src="<%=path %>/script/easyui-lang-zh_CN.js"></script>
  <script type="text/javascript" src="<%=path %>/script/dateFormat.js"></script>
  <script type="text/javascript" src="<%=path %>/script/datagrid-bufferview.js"></script>
  <script type="text/javascript" src="<%=path %>/script/common.js"></script>
  <script type="text/javascript" src="<%=path %>/script/zTree_v3/js/jquery.ztree.core-3.5.js"></script>  
  <script type="text/javascript" src="<%=path %>/script/zTree_v3/js/jquery.ztree.excheck-3.5.js"></script>  
  <script type="text/javascript" src="<%=path %>/script/zTree_v3/js/jquery.ztree.exedit-3.5.js"></script> 
  <style type="text/css">
    #fm{
      margin:0;
      padding:10px 30px;
    }
    .ftitle{
      font-size:14px;
      font-weight:bold;
      padding:5px 0;
      margin-bottom:10px;
      border-bottom:1px solid #ccc;
    }
    .fitem{
      margin-bottom:17px;
    }
    .fitem label{
      display:inline-block;
      width:80px;
    }
    .fitem input{
      width:230px;
    }
  </style>
</head>
<body>
<table id="tt" title="class" style="width:auto;height:830px">
</table>
<!-----------------------------------------------------------------按钮------------------------------------------------------------------->
<div id="toolbar" style="padding:5px;height:auto">
  <div>
  	<!--   父ID：<input id="parentId"  name="parentId" type="text" class="easyui-numberbox" style="width:150px" validType="length[0,10]" missingMessage="必须为数字" />&nbsp;&nbsp;
  	 用户名称：<input id="rightName"  name="rightName" type="text" class="easyui-textbox" validType="length[0,10]" style="width:150px" />&nbsp;&nbsp;
    <a href="javascript:void(0)"  class="easyui-linkbutton" iconCls="icon-search" onclick="searchSentence()">查询</a>-->
  
    <!-- 搜索条件结束 -->
    <a href="javascript:void(0)"  class="easyui-linkbutton" iconCls="icon-add" onclick="addAd()">添加</a>&nbsp;
    <a href="javascript:void(0)"  class="easyui-linkbutton" iconCls="icon-edit" onclick="editClass()">修改</a>&nbsp;
    <a href="javascript:void(0)"  class="easyui-linkbutton" iconCls="icon-remove" onclick="deleteClass()">删除</a>&nbsp;&nbsp;
    <a href="javascript:void(0)"  class="easyui-linkbutton" iconCls="icon-add" onclick="grantRole()">授予角色</a>&nbsp;&nbsp;

  </div>
</div>
<!-------------------------------------------------------------添加/编辑框 开始----------------------------------------------------------------------->
<!-- 添加/编辑框 开始-->
<div id="addad" class="easyui-dialog"
     style="width: 400px; height: 400px; padding: 10px 20px;"  closed="true"
     buttons="#dlg-buttons">
  <div class="ftitle">用户</div>
  <form id="inAddAd" method="post"  validate enctype="multipart/form-data">
    <input type="hidden" name="id" id="cls_id" />
    <div class="fitem">
      <label>用户名:</label>
      <input  class="easyui-textbox" name="username" id="username" value=""  validate required validType="length[0,64]"/>
    </div>
    <div class="fitem">
      <label>密码:</label>
      <input type="password" class="easyui-textbox" name="password" id="password" value="" required validate validType="length[0,64]"/>
    </div>
    <div class="fitem">
      <label>昵称:</label>
      <input  class="easyui-textbox" id="nickname" name="nickname"  value="" validate validType="length[0,64]" />
    </div>
    <div class="fitem">
      <label>手机号:</label>
      <input   class="easyui-textbox" id="mobile" name="mobile"  value="" validate validType="length[0,20]" />
    </div>
    <div class="fitem">
      <label>邮件:</label>
      <input  class="easyui-textbox" id="email" name="email"  value="" validate validType="length[0,64]" />
    </div>
    
  </form>
  <div id="dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton c6"  iconCls="icon-ok" onclick="saveOrUpdateAd()" style="width: 90px">Save</a> 
    <a href="javascript:void(0)" class="easyui-linkbutton"  iconCls="icon-cancel" onclick="closeDialog()" style="width: 90px">Cancel</a>
  </div>
</div>
<!------------------------------------------------------------------------------------------------------------------------------------>

<!-- 授予角色-->
<div id="addrole" class="easyui-dialog"
     style="width: 400px; height: 700px; padding: 10px 20px;"  closed="true"
     buttons="#dlg-buttons2">
  <div class="ftitle">用户</div>
    <div id="userIdDiv" class="fitem">
	    <input type="hidden" name="userId" id="userId" />
    </div>
    <div class="fitem">
      <label>角色:</label>
      <ul id="demo" class="ztree" style="height:420px;border:1px #000 solid;overflow:auto;"></ul>
    </div>
  <div id="dlg-buttons2">
    <a href="javascript:void(0)" class="easyui-linkbutton c6"  iconCls="icon-ok" onclick="saveUserRole()" style="width: 90px">Save</a> 
    <a href="javascript:void(0)" class="easyui-linkbutton"  iconCls="icon-cancel" onclick="closeUserDialog()" style="width: 90px">Cancel</a>
  </div>
</div>



</body>
<script type="text/javascript">
  $.ajaxSetup({cache:false,async:false});
  $(function(){
    $('#tt').datagrid({
      url:'<%=basePath %>authority/user/findAllUser',
      method:'get',
      singleSelect:true,toolbar:'#toolbar',remoteSort:false,pageSize:50,nowrap:false,
      fitColumns:true,pagination:false,rownumbers:true,
      columns:[[
        {field:'id',title:'ID',sortable:true,width:20,hidden:true},
        {field:'username',title:'用户名',sortable:true,width:30},
        {field:'password',title:'密码',sortable:true,width:30},
        {field:'nickname',title:'昵称',sortable:true,width:30},
        {field:'mobile',title:'手机',sortable:true,width:37},
        {field:'email',title:'电子邮件',sortable:true,width:50},
        {field:'genTime',title:'创建时间',sortable:true,width:50,formatter:function(value,row,index){  
            var unixTimestamp = new Date(value);  
            return unixTimestamp.toLocaleString();  
            }  
        }, 
        {field:'updateTime',title:'更新时间',sortable:true,width:50,formatter:function(value,row,index){  
            var unixTimestamp = new Date(value);  
            return unixTimestamp.toLocaleString();  
            }  
        }, 
        {field:'loginTime',title:'登录时间',sortable:true,width:50,formatter:function(value,row,index){  
            var unixTimestamp = new Date(value);  
            return unixTimestamp.toLocaleString();  
            }  
        }, 
        {field:'lastLoginTime',title:'最后登录时间',sortable:true,width:50,formatter:function(value,row,index){  
            var unixTimestamp = new Date(value);  
            return unixTimestamp.toLocaleString();  
            }  
        }, 
        {field:'count',title:'登录次数',sortable:true,width:50},
      ]],
    
    });
  });
//------------------------------------------------------------------------------------------
	//关闭弹出框
	function closeDialog(){
	  $('#addad').dialog('close') ;
	}
	//关闭弹出框
	function closeUserDialog(){
	  $('#addrole').dialog('close') ;
	}
	
	//添加用户
	function addAd(){
	  $('#addad').dialog('open').dialog('setTitle','添加用户');
	  $('#inAddAd').form('clear');
	  url = '<%=basePath%>authority/user/saveUser';
	}
	//修改用户
	function editClass(){
	  url = '<%=basePath%>authority/user/updateUser';
	  var row = $('#tt').datagrid('getSelected');
	  if (row){
	    $("#cls_id").val(row.id);
	    $("#username").val(row.username);
	    $("#password").val(row.password);
	    $("#nickname").val(row.nickname);
	    $("#mobile").val(row.mobile);
	    $("#email").val(row.email);
	    $("#genTime").val(row.genTime);
	    $('#addad').dialog('open').dialog('setTitle','用户编辑');
	    $('#inAddAd').form('load',row);
	  }
	}
	
	
	function deleteClass(){
	
	  var row = $('#tt').datagrid('getSelected');
	  if (row){
	    $.messager.confirm('提示','确定要删除这个用户吗？',function(r){
	      if (r){
	        $.post('<%=basePath%>authority/user/deleteUser',{id:row.id},function(result){
	        	$.messager.alert("提示",result.message);
	            $('#tt').datagrid('reload');    // reload the data
	          },'json');
	        }
	      });
	    }
	  }
	//---------------------------------------------------------------------------------------------------------------------------
	//添加或修改用户
	function saveOrUpdateAd(){
	
	  $('#inAddAd').form('submit', {
	    url : url,
	    onSubmit : function() {
	      return $(this).form('validate');
	    },
	    success : function(result) {
	  	var Data = eval('(' + result + ')');   	  
	      if (result.status) {
	        $.messager.show({
	          title : 'Error',
	          msg : '服务器出错，请稍后再试'
	        });
	      }else if(Data.status == '-1'){
	      	$.messager.show({
	              title : '提示',
	              msg : '此时有正在活动的单词,请先调整'
	            });
	      	return;
	      }else if(Data.status == '-2'){
	    	  $.messager.show({
	              title : '提示',
	              msg : '用户名不允许重复'
	            });
	      	return;
	      }else if(Data.status == '-3'){
	    	  $.messager.show({
	              title : '提示',
	              msg : '"admin" 此名称不可修改'
	            });
	      	return;
	      }else {
	        $('#addad').dialog('close'); // close the dialog
	        $('#tt').datagrid('reload'); // reload the data
	      }
	    }
	  });
	}



	function searchSentence(){
	 var parentId = $("#parentId").textbox("getValue");
	 var rightName = $("#rightName").textbox("getValue");
	 var url = '<%=basePath %>sentence/listAll?parentId='+parentId+'&rightName='+rightName;
	 url =encodeURI(encodeURI(url));
	 $("#tt").datagrid({
		 url:url,
		 method:'get',
		 onLoadSuccess:function(data){
			 if(data.total == null){
				 $.messager.alert("提示","没有查询到任何符合条件的数据")
			 }
		 }
	 });
	}
    //授予角色
	function grantRole(){
    	 row = $("#tt").datagrid("getSelected");
    	if(row){
			$("#userIdDiv").html(row.username);
			$("#userId").val(row.id);
			$("#addrole").dialog("open").dialog("setTitle","授予角色");
			 rData = new Array();
			 $.post("<%=basePath %>authority/user/getUserRole",{"userId":row.id},function(data){
					 rData = data;
			 });
			$.ajax({
				type: "GET",
		        dataType: "json",
		        traditional: true,
		        url: "<%=basePath %>authority/role/roleTree",
		        async: false,//表示同步执行
		        success: function (data, textStatus) {
		        	if(data !=null){
						treeObj = $.fn.zTree.init($("#demo"), setting, data);
						//回显 权限
		                var nodes = treeObj.getNodes();
		    		    var nodes2 = treeObj.transformToArray(nodes);
		 				for(var i=0;i<nodes2.length;i++){
		    				if(rData != null){
		    					for(var j=0;j<rData.length;j++){
				    				if(nodes2[i].id == rData[j].roleId){
				    					treeObj.checkNode(nodes2[i], true, true);
				    					treeObj.updateNode(nodes2[0]);
				    				}
		    					}
		    				}
		 				}
						//展开节点和判断
		                treeObj.expandAll(true);
		                setCheck();
		    			$("#py").bind("change", setCheck);
		    			$("#sy").bind("change", setCheck);
		    			$("#pn").bind("change", setCheck);
		    			$("#sn").bind("change", setCheck);
		        	}
		        },
		        complete: function (XMLHttpRequest, textStatus) { },
		        error: function (e) {
		            alert("获取测试类型统计数据失败，请刷新页面重新加载！");
		        }
			});
    	}else{
    		$.messager.alert("提示","请选择用户");
    	}
    	url="<%=basePath %>authority/user/saveUserRole";
	}
	//组织一棵树
	var setting = {
		check: {
			enable: true
		},
		data: {
			simpleData: {
				enable: true
			}
		}
	};
	var code;
	
	function setCheck() {
		var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
		py = $("#py").attr("checked")? "p":"",
		sy = $("#sy").attr("checked")? "s":"",
		pn = $("#pn").attr("checked")? "p":"",
		sn = $("#sn").attr("checked")? "s":"",
		type = { "Y":py + sy, "N":pn + sn};
		zTree.setting.check.chkboxType = type;
		showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
	}
	function showCode(str) {
		if (!code) code = $("#code");
		code.empty();
		code.append("<li>"+str+"</li>");
	}
	//保存用户角色关系
    function saveUserRole(){
    	var nodes = treeObj.getNodes();
		var nodes2 = treeObj.transformToArray(nodes);
		var roleIds = new Array();
		for(var i=0;i<nodes2.length;i++){
			var b = nodes2[i].checked;
			if(b==true || b == "true"){
				roleIds.push(nodes2[i].id);
			}
		}
		$.post("<%=basePath %>authority/user/saveUserRole",{"userId":row.id,"roleIds":roleIds.toString()},function(data){
			$.messager.alert("提示","权限添加成功");
			$('#addrole').dialog('close');
			$('#tt').datagrid('reload');
		});
    }

</script>
</html>
